<template>
  <div class="app-container">
    <div class="mainbox">
      <div class="filter-container">
        <el-form v-show="showSearch" ref="queryForm" :model="queryParams"
                 :inline="true" label-width="68px" @submit.native.prevent>
          <el-form-item label="模板名称" prop="templateName">
            <el-input
              v-model.trim="queryParams.templateName"
              placeholder="请输入内容"
              clearable
              size="small"
              maxlength="30"
              class="filter-item limit"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item label="消息类型" prop="typeId">
            <el-select v-model="queryParams.typeId" clearable placeholder="请选择">
              <el-option
                v-for="item in messageTypeList"
                :key="item.typeId"
                :label="item.typeName"
                :value="item.typeId"
              />
            </el-select>
          </el-form-item>
        </el-form>
        <div class="flex-1" />
        <div>
          <div class="flex-1" />
          <div style="display:flex;">
            <el-button type="primary" icon="el-icon-search" @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" @click="handleReset">重置</el-button>
          </div>
        </div>
      </div>
      <div class="table-container table-fullscreen">
        <div class="table-opt-container">
          <el-button
            v-permission="['TEMPLATE_ADD_BUTTON']"
            type="primary"
            icon="el-icon-plus"
            @click="handleAdd"
          >新增</el-button>
          <div class="flex-1" />
          <dt-dialog-column v-model="isShowTable" :columns="showColumns" :table-ref="$refs.table"
                            @queryTable="getList" />
        </div>
        <el-table v-if="isShowTable" ref="table" v-loading="loading"
                  border highlight-current-row :header-cell-style="{ backgroundColor: '#f2f2f2'}"
                  :data="TemplateList">
          <template slot="empty">
            <p>{{ $store.getters.dataText }}</p>
          </template>
          <el-table-column
            fixed="left"
            type="index"
            label="序号"
            width="70"
            :index="(index)=>(queryParams.pageNo - 1) * queryParams.pageSize + index + 1"
          />
          <el-table-column v-if="showColumns[0].show" key="templateName" label="模板名称"
                           show-overflow-tooltip align="center" prop="templateName" />
          <el-table-column v-if="showColumns[1].show" key="templateCode" label="模板编码"
                           show-overflow-tooltip align="center" prop="templateCode" />
          <el-table-column v-if="showColumns[2].show" key="typeName" label="消息类型"
                           show-overflow-tooltip align="center" prop="typeName" />
          <el-table-column v-if="showColumns[3].show" key="applyScene" label="适用场景"
                           show-overflow-tooltip align="center" prop="applyScene">
            <template slot-scope="scope">
              <dt-dict-tag :options="dict.type.applicable" :value="scope.row.applyScene" />
            </template>
          </el-table-column>
          <el-table-column v-if="showColumns[4].show" key="createTime" label="创建时间"
                           show-overflow-tooltip align="center" prop="createTime"
                           width="180">
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
            </template>
          </el-table-column>
          <el-table-column v-if="showColumns[5].show" key="createUserName" label="创建人"
                           show-overflow-tooltip align="center" prop="createUserName" />
          <el-table-column v-if="showColumns[6].show" key="updateTime" label="修改时间"
                           show-overflow-tooltip align="center" prop="updateTime"
                           width="180">
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.updateTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
            </template>
          </el-table-column>
          <el-table-column :key="Math.random()" label="操作" fixed="right"
                           align="center" class-name="small-padding fixed-width" width="280">
            <template slot-scope="scope">
              <el-button
                v-permission="['TEMPLATE_SEND_BUTTON']"
                size="small"
                @click="handleSend(scope.row)"
              >测试推送</el-button>
              <el-button
                v-permission="['TEMPLATE_UPDATE_BUTTON']"
                size="small"
                icon="el-icon-edit"
                @click="handleUpdate(scope.row)"
              >修改</el-button>
              <el-button
                v-permission="['TEMPLATE_DEL_BUTTON']"
                :disabled="handleIsDisabled(scope.row)"
                size="small"
                icon="el-icon-delete"
                type="danger"
                @click="handleDelete(scope.row)"
              >删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <dt-pagination
          v-show="total>0"
          :total="total"
          :page.sync="queryParams.pageNo"
          :limit.sync="queryParams.pageSize"
          @pagination="getList"
        />
      </div>
    </div>
    <!-- 添加或修改模板管理对话框 -->
    <dt-dialog :title="title" :visible.sync="open" :is-loading="loading"
               @comfirmBtn="submitForm" @closeDialog="cancel">
      <div slot="content">
        <el-form ref="form" :model="form" :rules="rules"
                 label-width="84px">
          <el-form-item label="模板名称" prop="templateName">
            <el-input v-model.trim="form.templateName" placeholder="请输入模板名称" maxlength="30"
                      show-word-limit class="limit" />
          </el-form-item>
          <el-form-item label="模板编码" prop="templateCode">
            <el-input v-model.trim="form.templateCode" :disabled="title=='修改模板'" placeholder="请输入模板编码"
                      maxlength="30" show-word-limit class="limit" />
          </el-form-item>
          <el-row :gutter="24">
            <el-col :span="24">
              <el-form-item label="消息类型" prop="typeObj">
                <el-select v-model="typeObj" value-key="typeId" clearable
                           placeholder="请选择消息类型" style="width:100%;" @change="selectType()">
                  <el-option
                    v-for="item in messageTypeList"
                    :key="item.typeId"
                    :label="item.typeName"
                    :value="item"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="优先级" prop="priorityLevel">
                <el-select v-model="form.priorityLevel" disabled clearable
                           placeholder="请选择优先级" style="width:100%">
                  <el-option
                    v-for="dict in dict.type.classifyLevel"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="适用场景" prop="applyScene">
                <el-select v-model="form.applyScene" clearable placeholder="请选择适用场景"
                           style="width:100%">
                  <el-option
                    v-for="dict in dict.type.applicable"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-form-item label="发送渠道" prop="channelObj">
            <el-select v-model="channelObj" value-key="channelId" clearable
                       multiple disabled placeholder="请选择发送渠道"
                       style="width:100%;">
              <el-option
                v-for="item in channelList"
                :key="item.channelId"
                :label="item.channelName"
                :value="item"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="模板标题" prop="templateTitle">
            <el-input
              v-model.trim="form.templateTitle"
              maxlength="80"
              placeholder="请输入模板标题，可根据需要设置占位符，如：
这是发给${name}的通知"
              type="textarea"
              show-word-limit
              class="limit"
            />
          </el-form-item>
          <el-form-item label="模板内容" prop="templateContent">
            <el-input
              v-model.trim="form.templateContent"
              type="textarea"
              maxlength="500"
              placeholder="请输入模板内容，可根据需要设置占位符，如：
你在DQBasic基础开发平台设置的登录密码还有${day}过期，请立即登录本站重设密码。"
              show-word-limit
              class="limit"
            />
          </el-form-item>
        </el-form>
      </div>
    </dt-dialog>
  </div>
</template>

<script>
import { listTemplate, getTemplate, delTemplate, addTemplate, updateTemplate, listMessageType, getChannelListByTypeCode } from '@/framework/api/template/Template'
import { uuId } from '@/framework/utils/uuid'
import { checkCode, checkChar } from '@/framework/utils/validate'

export default {
  name: 'Template',
  dicts: ['messageType', 'applicable', 'classifyLevel'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 显隐表格
      isShowTable: true,
      // 选中数组
      ids: [],
      // 列显隐数组
      showColumns: [
        { prop: 'templateName', label: '模板名称', show: true },
        { prop: 'templateCode', label: '模板编码', show: true },
        { prop: 'typeName', label: '消息类型', show: true },
        { prop: 'applyScene', label: '适用场景', show: true },
        { prop: 'createTime', label: '创建时间', show: true },
        { prop: 'createUserName', label: '创建人', show: true },
        { prop: 'updateTime', label: '修改时间', show: true }
      ],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 模板管理表格数据
      TemplateList: [],
      messageTypeList: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNo: 1,
        pageSize: 10,
        templateName: null,
        typeId: null
      },
      // 表单参数
      form: {},
      channelList: [],
      typeObj: {},
      channelObj: [],
      // 表单校验
      rules: {
        templateName: [
          { required: true,
            trigger: 'blur',
            validator: (rule, value, callback) => {
              if (!value) {
                callback(new Error('模板名称不能为空'))
              } else if (!checkChar(value)) {
                callback(new Error('请输入汉字、字母、数字或下划线'))
              } else {
                callback()
              }
            }
          }
        ],
        templateCode: [
          { required: true,
            trigger: 'blur',
            validator: (rule, value, callback) => {
              if (!value) {
                callback(new Error('模板编码不能为空'))
              } else if (!checkCode(value)) {
                callback(new Error('请输入字母、数字或下划线'))
              } else {
                callback()
              }
            }
          }
        ],
        templateContent: [
          { required: true, message: '模板内容不能为空', trigger: 'blur' }
        ],
        typeObj: [
          { required: true,
            trigger: 'blur',
            validator: (rule, value, callback) => {
              if (Object.keys(this.typeObj).length <= 0) {
                callback(new Error('消息类型不能为空'))
              } else {
                callback()
              }
            }
          }
        ],
        priorityLevel: [
          { required: true, message: '优先级不能为空', trigger: 'blur' }
        ],
        // applyScene: [
        //   { required: true, message: '适用场景不能为空', trigger: 'change' }
        // ],
        channelObj: [
          { required: true,
            trigger: 'blur',
            validator: (rule, value, callback) => {
              if (this.channelObj.length <= 0) {
                callback(new Error('发送渠道不能为空'))
              } else {
                callback()
              }
            }
          }
        ]
      }
    }
  },
  created() {
    this.initData()
  },
  methods: {
    initData() {
      this.getTypeList()
      this.getList()
    },
    /** 查询模板管理列表 */
    getList() {
      this.loading = true
      listTemplate(this.queryParams).then(({ data: response }) => {
        this.TemplateList = response.rows
        this.total = response.totalRows
        this.loading = false
      })
    },
    // 获取消息类型列表
    getTypeList() {
      listMessageType().then((res) => {
        this.messageTypeList = res.data
      })
    },
    getChannelId(val) {
      getChannelListByTypeCode(val).then((res) => {
        this.channelList = res.data
        this.channelObj = this.channelList.map((item) => {
          return item
        })
        this.form.channelId = this.channelObj.map((item) => {
          return item.channelId
        }).join(',')
      })
    },
    // 选择消息类型
    selectType() {
      this.form.typeId = this.typeObj.typeId
      this.form.priorityLevel = this.typeObj.priorityLevel
      this.getChannelId(this.typeObj.typeCode)
    },
    // 取消按钮
    cancel() {
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        templateId: null,
        templateName: null,
        templateCode: null,
        typeId: null,
        priorityLevel: null,
        applyScene: null,
        channelId: null,
        templateTitle: null,
        templateContent: null
      }
      this.typeObj = {}
      this.channelObj = []
      this.resetForm('form')
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNo = 1
      this.getList()
    },
    /** 重置按钮操作 */
    handleReset() {
      this.resetForm('queryForm')
      this.handleQuery()
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.form.templateCode = uuId(8)
      this.open = true
      this.title = '新增模板'
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      this.open = true
      this.title = '修改模板'
      getTemplate(row.templateId).then((response) => {
        this.form = response.data
        this.typeObj = this.messageTypeList.map((item) => {
          if (item.typeId === this.form.typeId) {
            return item
          } else {
            return null
          }
        })
        this.typeObj = this.typeObj.filter((item) => {
          return item != null
        })
        this.typeObj = this.typeObj[0]
        this.getChannelId(this.typeObj.typeCode)
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          if (this.form.templateId != null) {
            updateTemplate(this.form).then((response) => {
              this.$dtModal.msgSuccess('修改成功')
              this.open = false
              this.getList()
            })
          } else {
            addTemplate(this.form).then((response) => {
              this.$dtModal.msgSuccess('新增成功')
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      this.$dtModal.confirm(`是否确认删除模板名称为"${row.templateName}"的数据项？`).then(() => {
        return delTemplate(row.templateId)
      }).then(() => {
        this.getList()
        this.$dtModal.msgSuccess('删除成功')
      }).catch(() => {})
    },
    // 测试发送按钮
    handleSend(row) {
      this.$router.push({
        path: './testSend',
        query: {
          templateId: row.templateId
        }
      })
    },
    handleIsDisabled(data) {
      const arr = ['lockSmsCode', 'lockMailCode', 'emailVerificationCode', 'SMS_154950909', 'initPasswordEmail', 'SMS_259495445', 'flowworkNoticeTemplete', 'timerTemplete', 'noticeTemplate']
      if (arr.includes(data.templateCode)) {
        return true
      } else {
        return false
      }
    }
  }
}
</script>
